package com.jy.modules.cims.component.common;

import java.text.MessageFormat;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.jy.modules.cims.common.exception.CimsException;
import com.jy.modules.cims.common.sysUtils.CollectionsUtils;
import com.jy.modules.cims.common.sysUtils.SearchParamUtil;
import com.jy.modules.cims.common.sysUtils.SimpleStringUtils;
import com.jy.modules.cims.component.common.service.TCMmCreditPackageService;
import com.jy.modules.cims.data.common.dto.TCMmCreditPackageDTO;

/**
 * @description 通用债权债权包处理组件。
 * @author shengzhoutao
 * @date 2015-07-07 
 */
@Service("com.jy.modules.cims.component.common.CreditPackage")
public class CreditPackage {
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditPackageService")
	private TCMmCreditPackageService creditPackageService;

	/**
	 * 
	 * @param dto
	 * @throws Exception
	 */
	public void insertCreditPackageNoCheck(TCMmCreditPackageDTO dto) throws Exception {
		insertCreditPackage(dto, false);
	}

	/**
	 * 
	 * @param dto
	 * @param checkExistFlag
	 * @throws Exception
	 */
	public void insertCreditPackage(TCMmCreditPackageDTO dto, boolean checkExistFlag) throws Exception {
		// 查询债权包
		if (!SimpleStringUtils.hasText(dto.getCooperorgCode())) {
			throw new CimsException("合作机构编号为空！");
		}
		if (!SimpleStringUtils.hasText(dto.getContractCode())) {
			throw new CimsException("合约编号为空！");
		}
		if (!SimpleStringUtils.hasText(dto.getCreditPackageName())) {
			throw new CimsException("债权包名称为空！");
		}
		TCMmCreditPackageDTO searchDto = new TCMmCreditPackageDTO();
		searchDto.setCooperorgCode(dto.getCooperorgCode());
		searchDto.setContractCode(dto.getContractCode());
		searchDto.setCreditPackageName(dto.getCreditPackageName());
		List<TCMmCreditPackageDTO> creditPackageDTOList = creditPackageService.searchTCMmCreditPackage(SearchParamUtil.getSearchParam(searchDto));
		// 判断债权包是否存在
		if (CollectionsUtils.isEmpty(creditPackageDTOList)) {
			// 新增债权包
			creditPackageService.insertTCMmCreditPackage(dto);
		} else {
			if (checkExistFlag == true) {
				throw new Exception(MessageFormat.format("根据合作机构编号[{0}]、债权包名称[{1}]、合约编号[{2}]，查询债权包出现异常！",
						new Object[] { dto.getCooperorgCode(), dto.getCreditPackageName(), dto.getContractCode() }));
			}
		}
	}
}
